/**
 * @file id_generator.cpp
 * @brief 文件ID生成器实现
 */

#include "id_generator.h"
#include "hash_util.h"
#include "logger.hpp"
#include "database_manager.h"
#include <chrono>
#include <algorithm>

// Base62字符集定义
const char IdGenerator::BASE62_CHARS[62] = 
{
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
    'y', 'z'
};

/**
 * @brief 根据文件哈希生成6位ID
 */
std::string IdGenerator::generateFromHash(const std::string& hash) 
{
    if (hash.length() < 8) 
    {
        Log::GetLogger("asynclogger")->Info("哈希值长度不足，无法生成ID");
        return generateRandom();
    }
    
    // 取哈希值的前8个字符，转换为数值
    std::string hex_part = hash.substr(0, 8);
    uint64_t value = std::stoull(hex_part, nullptr, 16);
    
    // 生成4位主ID
    std::string main_id = toBase62(value, 4);
    
    // 计算2位校验码
    std::string checksum = calculateChecksum(main_id);
    
    return main_id + checksum;
}

/**
 * @brief 生成随机6位ID
 */
std::string IdGenerator::generateRandom() 
{
    auto& rng = getRandomEngine();
    std::uniform_int_distribution<uint64_t> dist(0, 62*62*62*62 - 1);  // 4位Base62的范围
    
    uint64_t value = dist(rng);
    std::string main_id = toBase62(value, 4);
    std::string checksum = calculateChecksum(main_id);
    
    return main_id + checksum;
}

/**
 * @brief 验证ID格式是否正确
 */
bool IdGenerator::validateId(const std::string& id) 
{
    // 检查长度
    if (id.length() != 6) 
    {
        return false;
    }
    
    // 检查字符是否都在Base62字符集中
    for (char c : id) 
    {
        if (std::find(BASE62_CHARS, BASE62_CHARS + 62, c) == BASE62_CHARS + 62) {
            return false;
        }
    }
    
    // 验证校验码
    std::string main_id = id.substr(0, 4);
    std::string checksum = id.substr(4, 2);
    std::string calculated_checksum = calculateChecksum(main_id);
    
    return checksum == calculated_checksum;
}

/**
 * @brief 生成唯一ID（避免数据库碰撞）
 */
std::string IdGenerator::generateUniqueId(const std::string& hash, int max_retries) 
{
    auto& db = DatabaseManager::getInstance();
    
    for (int i = 0; i < max_retries; ++i) 
    {
        std::string id;
        
        if (!hash.empty() && i == 0) 
        {
            // 第一次尝试使用哈希生成
            id = generateFromHash(hash);
        } 
        else 
        {
            // 后续尝试使用随机生成
            id = generateRandom();
        }
        
        // 检查数据库中是否已存在
        if (!db.isIdExists(id)) 
        {
            Log::GetLogger("asynclogger")->Info("生成唯一ID成功: %s (尝试次数: %d)", id.c_str(), i + 1);
            return id;
        }
        
        Log::GetLogger("asynclogger")->Info("ID碰撞，重新生成: %s", id.c_str());
    }
    
    Log::GetLogger("asynclogger")->Info("生成唯一ID失败，已达到最大重试次数: %d", max_retries);
    return "";
}

/**
 * @brief 将数值转换为Base62字符串
 */
std::string IdGenerator::toBase62(uint64_t value, int length) 
{
    std::string result;
    result.reserve(length);
    
    for (int i = 0; i < length; ++ i) 
    {
        result = BASE62_CHARS[value % 62] + result;
        value /= 62;
    }
    
    return result;
}

/**
 * @brief 从Base62字符串转换为数值
 */
uint64_t IdGenerator::fromBase62(const std::string& str) 
{
    uint64_t result = 0;
    uint64_t base = 1;
    
    for (int i = str.length() - 1; i >= 0; --i) 
    {
        char c = str[i];
        int value = 0;
        
        if (c >= '0' && c <= '9') 
        {
            value = c - '0';
        } 
        else if (c >= 'A' && c <= 'Z') 
        {
            value = c - 'A' + 10;
        } 
        else if (c >= 'a' && c <= 'z') 
        {
            value = c - 'a' + 36;
        }
        
        result += value * base;
        base *= 62;
    }
    
    return result;
}

/**
 * @brief 计算校验码
 */
std::string IdGenerator::calculateChecksum(const std::string& id) 
{
    // 使用简单的校验算法：将主ID的Base62值求和取模
    uint64_t sum = 0;
    for (char c : id) 
    {
        if (c >= '0' && c <= '9') 
        {
            sum += c - '0';
        } 
        else if (c >= 'A' && c <= 'Z') 
        {
            sum += c - 'A' + 10;
        } 
        else if (c >= 'a' && c <= 'z') 
        {
            sum += c - 'a' + 36;
        }
    }
    
    // 生成2位校验码
    uint64_t checksum_value = sum % (62 * 62);
    return toBase62(checksum_value, 2);
}

/**
 * @brief 获取随机数生成器
 */
std::mt19937& IdGenerator::getRandomEngine() 
{
    // 使用线程局部存储的随机数生成器
    thread_local std::mt19937 rng(
        std::chrono::steady_clock::now().time_since_epoch().count()
    );
    return rng;
} 